package cn.hxzy.course.controller;


import cn.hxzy.common.domain.Chapter;
import cn.hxzy.common.response.R;
import cn.hxzy.common.response.StatusEnum;
import cn.hxzy.course.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author niuyi
 * @since 2024-06-22
 */
@RestController
@RequestMapping("/chapter")
@CrossOrigin
public class ChapterController {

    @Autowired
    private ChapterService chapterService;

    /**
     * 根据课程ID查询所有的章节
     *
     * @return
     */
    @GetMapping("/select")
    public R<List<Chapter>> courseList(@RequestParam Integer courseId) {
        List<Chapter> chapters = chapterService.courseList(courseId);
        if (!chapters.isEmpty()) {
            return R.success(chapters);
        }
        return R.error(StatusEnum.SERVICE_ERROR);
    }

    /**
     * 创建章节(某个课程下面的章节)
     *
     * @return
     */

    @PostMapping("/increaseChapter")
    public R increaseChapter(@RequestBody Chapter chapter) {
        int i = chapterService.increaseChapter(chapter);
        if (i == 0) {
            return R.success("新增失败");
        }else if (i == 1) {
            return R.success("新增成功");
        } else if (i == 2) {
            return R.success("章节名称重复");
        }
        return R.error(StatusEnum.SERVICE_ERROR);
    }

    /**
     * 根据章节ID修改某章节名称
     *
     * @param chapterId
     * @return
     */
    @PutMapping("/update")
    public R updateChapter(@RequestParam Integer chapterId, @RequestParam String chapterName) {
        int i = chapterService.updateChapter(chapterId, chapterName);
        if (i > 0) {
            return R.success("修改成功");

        }
        return R.error(StatusEnum.SERVICE_ERROR);
    }

    /**
     * 根据章节ID删除该章节
     *
     * @return
     */
    @DeleteMapping("/delete")
    public R deleteById(@RequestParam Integer chapterId) {
        boolean b = chapterService.removeById(chapterId);
        if (b) {
            return R.success("删除成功");
        }
        return R.error(StatusEnum.SERVICE_ERROR);
    }


    @GetMapping("/getChapterNameById")
    public R<String> getChapterNameById(@RequestParam("chapterId") Integer chapterId) {
        Chapter byId = chapterService.getById(chapterId);
        return R.success(byId.getChapterName());
    }
}

